package com.bazaaroid.mobile.android.db;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Date;
import java.sql.Time;
//import java.util.ArrayList;

//import com.google.android.maps.GeoPoint;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class DbBazaaHelper extends SQLiteOpenHelper {

	private static String DB_PATH = "/data/data/com.bazaaroid.mobile.android/databases/";
	private static String DB_NAME = "Bazaa";
	private static int DB_VERSION = 1;
	
	private static String TAG = "[DbBazaaHelper]";
	
	/*
	 * Tables
	 */
	private static String TABLE_ADDRESS = "address";
	private static String TABLE_CATEGORY = "category";
	private static String TABLE_CONTACT = "contact";
	private static String TABLE_DISCOUNT = "discount";
	private static String TABLE_LOCATION = "location";
	private static String TABLE_PARTNER = "partner";
	private static String TABLE_PARTNER_LOCATION = "partnerlocation";
	private static String TABLE_PRODUCT = "product";
	private static String TABLE_PRODUCT_CATEGORY = "productcategory";
	private static String TABLE_PRODUCT_LOCATION = "productlocation";
	private static String TABLE_PRODUCT_TAG = "producttag";	
	
	/*
	 * Database Columns Creation strings
	 */
	private static String CREATE_TABLE_ADDRESS;
	private static String CREATE_TABLE_CATEGORY;
	private static String CREATE_TABLE_CONTACT;
	private static String CREATE_TABLE_DISCOUNT;
	private static String CREATE_TABLE_LOCATION;
	private static String CREATE_TABLE_PARTNER;
	private static String CREATE_TABLE_PARTNER_LOCATION;
	private static String CREATE_TABLE_PRODUCT;
	private static String CREATE_TABLE_PRODUCT_CATEGORY;
	private static String CREATE_TABLE_PRODUCT_LOCATION;
	private static String CREATE_TABLE_PRODUCT_TAG;
	private static String CREATE_DATABASE;
	
	private SQLiteDatabase bazaaDB;
	
	private final Context bazaaContext;
	
	public DbBazaaHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
		Log.d(TAG, "Entered c-tor...");
		Log.d(TAG, String.format("Package: '%s'", this.getClass().getPackage().getName()));
		// TODO Auto-generated constructor stub
		this.bazaaContext = context;
		initCreationStrings();
		try
		{
			createDataBase();
		}
		catch(SQLException sqlException)
		{
			Log.e(TAG, String.format("SQL Exception: %s", sqlException.getMessage()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e(TAG, String.format("IO Exception: %s", e.getMessage()));
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		/*bazaaDB.execSQL(CREATE_TABLE_ADDRESS);
		bazaaDB.execSQL(CREATE_TABLE_CATEGORY);
		bazaaDB.execSQL(CREATE_TABLE_CONTACT);
		bazaaDB.execSQL(CREATE_TABLE_DISCOUNT);
		bazaaDB.execSQL(CREATE_TABLE_LOCATION);
		bazaaDB.execSQL(CREATE_TABLE_PARTNER);
		bazaaDB.execSQL(CREATE_TABLE_PARTNER_LOCATION);
		bazaaDB.execSQL(CREATE_TABLE_PRODUCT);
		bazaaDB.execSQL(CREATE_TABLE_PRODUCT_CATEGORY);
		bazaaDB.execSQL(CREATE_TABLE_PRODUCT_LOCATION);
		bazaaDB.execSQL(CREATE_TABLE_PRODUCT_TAG);*/
		//Log.d(TAG, String.format("Executing SQL statement: %s", CREATE_DATABASE));
		//db.execSQL(CREATE_DATABASE);
		Log.d(TAG, "Creating Address table...");
		db.execSQL(CREATE_TABLE_ADDRESS);
		Log.d(TAG, "Creating Category table...");
		db.execSQL(CREATE_TABLE_CATEGORY);
		Log.d(TAG, "Creating Contact table...");
		db.execSQL(CREATE_TABLE_CONTACT);
		Log.d(TAG, "Creating Discount table...");
		db.execSQL(CREATE_TABLE_DISCOUNT);
		Log.d(TAG, "Creating Location table...");
		db.execSQL(CREATE_TABLE_LOCATION);
		Log.d(TAG, "Creating Partner table...");
		db.execSQL(CREATE_TABLE_PARTNER);
		Log.d(TAG, "Creating PartnerLocation table...");
		db.execSQL(CREATE_TABLE_PARTNER_LOCATION);
		Log.d(TAG, "Creating Product table...");
		db.execSQL(CREATE_TABLE_PRODUCT);
		Log.d(TAG, "Creating ProductCategory table...");
		db.execSQL(CREATE_TABLE_PRODUCT_CATEGORY);
		Log.d(TAG, "Creating ProductLocation table...");
		db.execSQL(CREATE_TABLE_PRODUCT_LOCATION);
		Log.d(TAG, "Creating ProductTag table...");
		db.execSQL(CREATE_TABLE_PRODUCT_TAG);		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
	}

	private void initCreationStrings()
	{
		Log.d(TAG, "Initializing database creation strings...");
		CREATE_TABLE_ADDRESS =		"CREATE TABLE Address (" +
							" ID          integer PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE DEFAULT NULL," +
							" Street      text NOT NULL," +
							" Number      text NOT NULL," +
							" City        text NOT NULL," +
							" PostalCode  text NOT NULL," +
							" Township    text," +
							" State       text," +
							" Country     text" +
							");";

		CREATE_TABLE_CATEGORY =	"CREATE TABLE Category (" +
							" ID    integer PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE," +
							" Name  text NOT NULL UNIQUE" +
							");";

		CREATE_TABLE_CONTACT = 	"CREATE TABLE Contact (" +
							" ID         integer PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE DEFAULT NULL," +
							" Telephone  text DEFAULT NULL," +
							" Mobile     text DEFAULT NULL," +
							" Fax        text DEFAULT NULL," +
							" EMail      text DEFAULT NULL," +
							" Site       text DEFAULT NULL" +
							");";

		CREATE_TABLE_DISCOUNT = 	"CREATE TABLE Discount (" +
							" ID                 integer PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE," +
							" Name               varchar(64) NOT NULL," +
							" Description        varchar(1024)," +
							" Percentage         float(2,2) NOT NULL," +
							" PriceWithDiscount  float(10,2)," +
							" DateFrom           date," +
							" DateTo             date," +
							" ProductID          integer" +
							");";

		CREATE_TABLE_LOCATION =			"CREATE TABLE Location (" +
									" ID			integer PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE," +
									" Name			text NOT NULL," +
									" Longitude		real NOT NULL," +
									" Latitude   	real NOT NULL," +
									" OpeningHours	text," +
									" AddressID		integer," +
									" PartnerID		integer" +
									");";

		CREATE_TABLE_PARTNER =				"CREATE TABLE Partner (" +
									" ID           integer PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE DEFAULT NULL," +
									" Name         varchar(64) NOT NULL DEFAULT NULL," +
									" Description  varchar(1024) DEFAULT NULL," +
									" ContactID    integer NOT NULL" +
									");";

		CREATE_TABLE_PARTNER_LOCATION =	"CREATE TABLE PartnerLocation (" +
									" PartnerID   integer NOT NULL," +
									" LocationID  integer NOT NULL" +
									");";

		CREATE_TABLE_PRODUCT =				"CREATE TABLE Product (" +
									" ID           integer PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE," +
									" Name         text NOT NULL," +
									" Description  text," +
									" PartnerID    integer NOT NULL," +
									" Price        float(10,2)," +
									" Currency     text," +
									" DiscountID   integer" +
									");";

		CREATE_TABLE_PRODUCT_CATEGORY =	"CREATE TABLE ProductCategory (" +
									" ProductID   integer NOT NULL," +
									" CategoryID  integer NOT NULL" +
									");";

		CREATE_TABLE_PRODUCT_LOCATION =	"CREATE TABLE ProductLocation (" +
									" LocatoinID  integer NOT NULL," +
									" ProductID   integer NOT NULL" +
									");";

		CREATE_TABLE_PRODUCT_TAG =			"CREATE TABLE ProductTag (" +
									" tag        text NOT NULL," +
									" ProductID  integer NOT NULL" +
									");";
		
		CREATE_DATABASE =	CREATE_TABLE_ADDRESS +
							CREATE_TABLE_CATEGORY +
							CREATE_TABLE_CONTACT +
							CREATE_TABLE_DISCOUNT + 
							CREATE_TABLE_LOCATION +
							CREATE_TABLE_PARTNER +
							CREATE_TABLE_PARTNER_LOCATION +
							CREATE_TABLE_PRODUCT +
							CREATE_TABLE_PRODUCT_CATEGORY + 
							CREATE_TABLE_PRODUCT_LOCATION + 
							CREATE_TABLE_PRODUCT_TAG;
	}
	
	public void createDataBase() throws IOException{
		boolean exists = checkDataBase();
		
		if(exists)
		{
			// Database exists
			Log.d(TAG, "Database already exists.");
		}
		else
		{
			Log.d(TAG, "Database doesn't exists... Creating database...");
			//SQLiteDatabase db;
			try {
				bazaaDB = this.getReadableDatabase();
				
				Log.d(TAG, String.format("Database path = %s", bazaaDB.getPath()));				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.e(TAG, e.getMessage());
			}

			/*try
			{
				copyDataBase();
			}
			catch(IOException e)
			{
				throw new Error("Error copying database");
			}*/
		}
	}
	
	public boolean databaseExists()
	{
		return checkDataBase();
	}
	
	private boolean checkDataBase(){
		//SQLiteDatabase checkDB = null;
		
		try
		{
			String path = DB_PATH + DB_NAME;
			bazaaDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
		}
		catch(SQLiteException e)
		{
			Log.d("[DbBazaaHelper]", e.getMessage());
		}
		
		if(bazaaDB != null)
		{
			bazaaDB.close();
		}
		
		return bazaaDB != null ? true : false;
	}
	
	private void copyDataBase() throws IOException
	{
		InputStream input = bazaaContext.getAssets().open(DB_NAME);
		
		String outputFileName = DB_PATH + DB_NAME;
		
		OutputStream output = new FileOutputStream(outputFileName);
		
		byte[] buffer = new byte[1024];
		int length;
		while((length = input.read(buffer)) > 0)
		{
			output.write(buffer, 0, length);
		}
		
		output.flush();
		output.close();
		input.close();
	}
	
	public void openDataBase(boolean isReadOnly) throws SQLException
	{
		String path = DB_PATH + DB_NAME;
		
		bazaaDB = SQLiteDatabase.openDatabase(path, null, isReadOnly ? SQLiteDatabase.OPEN_READONLY : SQLiteDatabase.OPEN_READWRITE);
	}
	
	public synchronized void close()
	{
		if(bazaaDB != null)
		{
			bazaaDB.close();
		}
		
		super.close();
	}
	
	/*
	 * QUERIES
	 */
    
    public long insertAddress(String street, String number, String city, String postalCode, String township, String state, String country)
    {
    	ContentValues values = new ContentValues();
    	values.put("street", street);
    	values.put("number", number);
    	values.put("city", city);
    	values.put("postalcode", postalCode);
    	values.put("township", township);
    	values.put("state", state);
    	values.put("country", country);
    	return bazaaDB.insert(TABLE_ADDRESS, null, values);
    }
    
    public long insertCategory(String name)
    {
    	ContentValues values = new ContentValues();
    	values.put("name", name);
    	return bazaaDB.insert(TABLE_CATEGORY, null, values);
    }
    
    public long insertContact(String telephone, String mobile, String fax, String email, String site)
    {
    	ContentValues values = new ContentValues();
    	values.put("telephone", telephone);
    	values.put("mobile", mobile);
    	values.put("fax", fax);
    	values.put("email", email);
    	values.put("site", site);
    	return bazaaDB.insert(TABLE_CONTACT, null, values);
    }
    
    public long insertLocation(String name, double /*int*/ longitude, double latitude, String openingHours, int addressID, int partnerID)
    {
    	ContentValues values = new ContentValues();
    	values.put("name", name);
    	values.put("longitude", longitude);
    	values.put("latitude", latitude);
    	values.put("openingHours", openingHours);
    	values.put("addressId", addressID);
    	values.put("partnerId", partnerID);
    	return bazaaDB.insert(TABLE_LOCATION, null, values);
    }
    
    public long insertPartner(String name, String description, int contactID)
    {
    	ContentValues values = new ContentValues();
    	values.put("name", name);
    	values.put("description", description);
    	values.put("contactId", contactID);
    	return bazaaDB.insert(TABLE_PARTNER, null, values);
    }
    
    public long insertProduct(String name, String description, int partnerID, float price, String currency, int discountID)
    {
    	ContentValues values = new ContentValues();
    	values.put("name", name);
    	values.put("description", description);
    	values.put("partnerId", partnerID);
    	values.put("price", price);
    	values.put("currency", currency);
    	values.put("discountId", discountID);
    	return bazaaDB.insert(TABLE_PRODUCT, null, values);
    }
    
    public long insertProductTag(String tag, int productID)
    {
    	ContentValues values = new ContentValues();
    	values.put("tag", tag);
    	values.put("productId", productID);
    	return bazaaDB.insert(TABLE_PRODUCT_TAG, null, values);
    }
    
    public long insertProductLocation(int locationID, int productID)
    {
    	ContentValues values = new ContentValues();
    	values.put("locatoinId", locationID);
    	values.put("productId", productID);
    	return bazaaDB.insert(TABLE_PRODUCT_LOCATION, null, values);
    }
    
    public long insertProductCategory(int productID, int categoryID)
    {
    	ContentValues values = new ContentValues();
    	values.put("productId", productID);
    	values.put("categoryId", categoryID);
    	return bazaaDB.insert(TABLE_PRODUCT_CATEGORY, null, values);
    }
    
    public long insertPartnerLocation(int partnerID, int locationID)
    {
    	ContentValues values = new ContentValues();
    	values.put("partnerId", partnerID);
    	values.put("locationId", locationID);
    	return bazaaDB.insert(TABLE_PARTNER_LOCATION, null, values);
    }
    
    public long insertDiscount(String name, String description, float percentage, float priceWithDiscount, java.util.Date dateFrom, java.util.Date dateTo, int productID)
    {
    	ContentValues values = new ContentValues();
    	values.put("name", name);
    	values.put("description", description);
    	values.put("percentage", percentage);
    	values.put("priceWithDiscount", priceWithDiscount);
    	values.put("dateFrom", dateFrom.toString());
    	values.put("dateTo", dateTo.toString());
    	values.put("productId", productID);
    	return bazaaDB.insert(TABLE_DISCOUNT, null, values);
    }
    
    // get
    
    /*
     * getAddresses - returns all records from the Address table
     */
    public Cursor getAddresses()
    {
    	String[] arrColumns = {"ID", "Street", "Number", "City", "PostalCode", "Township", "State", "Country"};
    	return bazaaDB.query(TABLE_ADDRESS, arrColumns, null, null, null, null, null);
    }
    
    /*
     * getAddress - returns a record from Address table by given value of the ID
     */
    public Cursor getAddress(int addressId) throws SQLException
    {
    	String[] arrColumns = {"ID", "Street", "Number", "City", "PostalCode", "Township", "State", "Country"};
    	String sQuery = "ID=" + addressId;
    	Cursor cursor = bazaaDB.query(true, TABLE_ADDRESS, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    public Cursor getAddress(String street, String number, String city, String postalCode, String township, String state, String country)
    {
    	String[] arrColumns = {"ID", "Street", "Number", "City", "PostalCode", "Township", "State", "Country"};
    	String sQuery = String.format("Street like '%%%s%%' and Number like '%%%s%%' and City like '%%%s%%' and PostalCode like '%%%s%%' and Township like '%%%s%%' and State like '%%%s%%' and Country like '%%%s%%'", 
    			street, number, city, postalCode, township, state, country);
    	Log.d(TAG, String.format("Executing SQL query: %s", sQuery));
    	Cursor cursor = bazaaDB.query(true, TABLE_ADDRESS, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    /*
     * getCategories - returns all records from the Category table
     */
    public Cursor getCategories()
    {
    	String[] arrColumns = {"ID", "Name"};
    	return bazaaDB.query(TABLE_CATEGORY, arrColumns, null, null, null, null, null);
    }
    
    /*
     * getCategory - returns a record from Category table by given value of the ID
     */
    public Cursor getCategory(int categoryId) throws SQLException
    {
    	String[] arrColumns = {"ID", "Name"};
    	String sQuery = "ID=" + categoryId;
    	Cursor cursor = bazaaDB.query(true, TABLE_CATEGORY, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    public Cursor getContacts()
    {
    	String[] arrColumns = {"ID", "Telephone", "Mobile", "Fax", "EMail", "Site"};
    	return bazaaDB.query(TABLE_CONTACT, arrColumns, null, null, null, null, null);
    }
    
    public Cursor getContact(int contactId) throws SQLException
    {
    	String[] arrColumns = {"ID", "Telephone", "Mobile", "Fax", "EMail", "Site"};
    	String sQuery = "ID=" + contactId;
    	Cursor cursor = bazaaDB.query(true, TABLE_CONTACT, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    public Cursor getContact(String telephone, String mobile, String fax, String email, String site) throws SQLException
    {
    	String[] arrColumns = {"ID", "Telephone", "Mobile", "Fax", "EMail", "Site"};
    	String sQuery = String.format("Telephone like '%%%s%%' and Mobile like '%%%s%%' and Fax like '%%%s%%' and EMail like '%%%s%%' and Site like '%%%s%%'", 
    			telephone, mobile, fax, email, site);
    	Log.d(TAG, String.format("SQL query string: %s", sQuery));
    	Cursor cursor = bazaaDB.query(true, TABLE_CONTACT, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    public Cursor getLocations()
    {
    	String[] arrColumns = {"ID", "Name", "Longitude", "Latitude", "OpeningHours", "AddressID", "PartnerID"};
    	return bazaaDB.query(TABLE_LOCATION, arrColumns, null, null, null, null, null);
    }
    
    public Cursor getLocationsByPartner(int partnerId) throws SQLException
    {
    	String[] arrColumns = {"ID", "Name", "Longitude", "Latitude", "OpeningHours", "AddressID", "PartnerID"};
    	String sQuery = "PartnerID=" + partnerId;
    	Cursor cursor = bazaaDB.query(true, TABLE_LOCATION, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;    	
    }
    
    public Cursor getLocation(int locationId) throws SQLException
    {
    	String[] arrColumns = {"ID", "Name", "Longitude", "Latitude", "OpeningHours", "AddressID", "PartnerID"};
    	String sQuery = "ID=" + locationId;
    	Cursor cursor = bazaaDB.query(true, TABLE_LOCATION, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    public Cursor getLocations(double longitude, double latitude, float radius)
    {
    	// TODO: Create appropriate logic
    	// radius bi trebalo da izrazava poluprecnik u metrima - treba ubaciti logiku koja racuna odgovarajuce parametre shodno tome
    	// SQL upit bi trebao da trazi sve lokacije cije se longitude i latitude nalaze u odredjenom opsegu
    	return null;
    }
    
    public Cursor getPartners()
    {
    	String[] arrColumns = {"ID", "Name", "Description", "ContactID"};
    	SQLiteDatabase db = this.getReadableDatabase();
    	Cursor cursor = db.query(TABLE_PARTNER, arrColumns, "", null, null, null, null);
    	return cursor;
//    	return bazaaDB.query(TABLE_PARTNER, arrColumns, null, null, null, null, null);    	
    }
    
    public Cursor getPartner(int partnerId) throws SQLException
    {
    	String[] arrColumns = {"ID", "Name", "Description", "ContactID"};
    	String sQuery = "ID=" + partnerId;
    	SQLiteDatabase db = this.getReadableDatabase();
    	Cursor cursor = db.query(true, TABLE_PARTNER, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;    	
    }
    
    public Cursor getPartner(String name) throws SQLException
    {
    	String[] arrColumns = {"ID", "Name", "Description", "ContactID"};
    	String sQuery = String.format("Name like '%%%s%%'", name);
    	Cursor cursor = bazaaDB.query(true, TABLE_PARTNER, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;    	
    }
    
    public Cursor getProducts()
    {
    	String[] arrColumns = {"ID", "Name", "Description", "PartnerID", "Price", "Currency", "DiscountID"};
    	return bazaaDB.query(TABLE_PRODUCT, arrColumns, null, null, null, null, null);      	
    }
    
    public Cursor getProducts(String firstOptionQuery, String secondOptionQuery, int minPrice, int maxPrice, int discount, String categoryName, String partnerName)
    {
    	String[] arrColumns = {"ID", "Name", "Description", "PartnerID", "Price", "Currency", "DiscountID"};
    	String sQuery = "";/*String.format("Street like '%%%s%%' and Number like '%%%s%%' and City like '%%%s%%' and PostalCode like '%%%s%%' and Township like '%%%s%%' and State like '%%%s%%' and Country like '%%%s%%'", 
    			street, number, city, postalCode, township, state, country);*/
    	/*
    	SELECT *
    	FROM product INNER JOIN productcategory
    	   ON product.id = productcategory.productid
    	inner join category
    		on productcategory.categoryid = category.id
    	where category.name like 'Category_14%'
    	*/
    	/*
    	String.format("select * from Product " +
    			"inner join ProductCategory" +
    			"on Product.ID = ProductCategory.ProductID" +
    			"inner join Category" +
    			"on ProductCategory.CategoryID = Category.ID" +
    			"where Category.Name like '%%%s%%'" +
    			"and Product.Price <= %d" +
    			"and Product.Price >= %d" +
    			*/
    	
    	
    	Log.d(TAG, String.format("Executing SQL query: %s", sQuery));
    	//Cursor cursor = bazaaDB.query(true, TABLE_ADDRESS, arrColumns, sQuery, null, null, null, null, null);
    	Cursor cursor = bazaaDB.rawQuery(sQuery, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    public Cursor getProduct(int productId) throws SQLException
    {
    	String[] arrColumns = {"ID", "Name", "Description", "PartnerID", "Price", "Currency", "DiscountID"};
    	String sQuery = "ID=" + productId;
    	Cursor cursor = bazaaDB.query(true, TABLE_PRODUCT, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    public Cursor getProduct(String name) throws SQLException
    {
    	String[] arrColumns = {"ID", "Name", "Description", "PartnerID", "Price", "Currency", "DiscountID"};
    	String sQuery = String.format("Name like '%%%s%%'", name);
    	Cursor cursor = bazaaDB.query(true, TABLE_PRODUCT, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    } 
    
    public Cursor getProducts(String name) throws SQLException
    {
    	
    	try 
    	{
			String[] arrColumns = {"ID", "Name", "Description", "PartnerID", "Price", "Currency", "DiscountID"};
			String sQuery = String.format("Name like '%%%s%%'", name);
			SQLiteDatabase db = this.getReadableDatabase();
			
			
			if(db == null)
			{
				Log.e(TAG, "Database is null!!!");
			}
			Cursor cursor = db.query(TABLE_PRODUCT, arrColumns, sQuery, null, null, null, null, null);
			
			//Cursor cursor = db.rawQuery("select * from product", null);
			return cursor;
		}
    	/*catch (SQLException sqle)
    	{
    		Log.e(TAG, String.format("SQL error message: %s", sqle.getMessage()));
    	}
    	catch (SQLiteException se)
    	{
    		Log.e(TAG, String.format("SQLite error message: %s", se.getMessage()));
    	}*/
    	catch (Exception e) 
		{
			// TODO Auto-generated catch block
    		e.printStackTrace();
			Log.e(TAG, String.format("Error message: %s", e.getMessage()));
		}
    	return null;
    }     
    
    public Cursor getProductTags(int productId) throws SQLException
    {
    	String[] arrColumns = {"Tag", "ProductID"};
    	String sQuery = "ProductID = " + productId;
    	SQLiteDatabase db = this.getReadableDatabase();
    	Cursor cursor = db.query(true, TABLE_PRODUCT_TAG, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    public Cursor getDiscounts()
    {
    	String[] arrColumns = {"ID", "Name", "Description", "Percentage", "PriceWithDiscount", "DateFrom", "DateTo", "ProductID"};
    	return bazaaDB.query(TABLE_DISCOUNT, arrColumns, null, null, null, null, null);      	
    }
    
    public Cursor getDiscount(int discountId) throws SQLException
    {
    	String[] arrColumns = {"ID", "Name", "Description", "Percentage", "PriceWithDiscount", "DateFrom", "DateTo", "ProductID"};
    	String sQuery = "ID=" + discountId;
    	Cursor cursor = bazaaDB.query(true, TABLE_DISCOUNT, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    public Cursor getDiscount(String name) throws SQLException
    {
    	String[] arrColumns = {"ID", "Name", "Description", "Percentage", "PriceWithDiscount", "DateFrom", "DateTo", "ProductID"};
    	String sQuery = String.format("Name like '%%%s%%'", name);
    	Cursor cursor = bazaaDB.query(true, TABLE_DISCOUNT, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }
    
    
    
    // ---- ova funkcija ide u DbBazaa klasu ----- //
    /*public Cursor getProductLocations(int productId) throws SQLException
    {
    	GeoPoint geoPoint;
    	
    	ArrayList<GeoPoint> arrLocations = new ArrayList<GeoPoint>();
    	String[] arrColumns = {"LocationID", "ProductID"};
    	String sQuery = "Name like '%" + name + "%'";
    	Cursor cursor = bazaaDB.query(true, TABLE_PRODUCT, arrColumns, sQuery, null, null, null, null, null);
    	if(cursor != null)
    	{
    		cursor.moveToFirst();
    	}
    	return cursor;
    }*/
    
    /*
    //---deletes a particular title---
    public boolean deleteTitle(long rowId) 
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    //---retrieves all the titles---
    public Cursor getAllTitles() 
    {
        return db.query(DATABASE_TABLE, new String[] {
        		KEY_ROWID, 
        		KEY_ISBN,
        		KEY_TITLE,
                KEY_PUBLISHER}, 
                null, 
                null, 
                null, 
                null, 
                null);
    }

    //---retrieves a particular title---
    public Cursor getTitle(long rowId) throws SQLException 
    {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {
                		KEY_ROWID,
                		KEY_ISBN, 
                		KEY_TITLE,
                		KEY_PUBLISHER
                		}, 
                		KEY_ROWID + "=" + rowId, 
                		null,
                		null, 
                		null, 
                		null, 
                		null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    //---updates a title---
    public boolean updateTitle(long rowId, String isbn, 
    String title, String publisher) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_ISBN, isbn);
        args.put(KEY_TITLE, title);
        args.put(KEY_PUBLISHER, publisher);
        return db.update(DATABASE_TABLE, args, 
                         KEY_ROWID + "=" + rowId, null) > 0;
    }*/    
}
